package com.ifast.common.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ifast.api.config.LoginConfig;
import com.ifast.common.annotation.Log;
import com.ifast.common.base.BaseController;
import com.ifast.common.domain.LogDO;
import com.ifast.common.service.LogService;
import com.ifast.common.utils.Result;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.graylog2.syslog4j.Syslog;
import org.graylog2.syslog4j.SyslogConstants;
import org.graylog2.syslog4j.SyslogIF;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * 日志
 * </pre>
 *
 * <small> 2018年3月23日 | Aron</small>
 */
@RequestMapping("/common/log")
@Controller
public class LogController extends BaseController {
    @Autowired
    LogService logService;
    String prefix = "common/log";

    @GetMapping()
    String log() {
        return prefix + "/log";
    }

    @ResponseBody
    @PostMapping("/list")
    public Result<Page<LogDO>> list(@RequestBody LogDO logDTO) {
        EntityWrapper<LogDO> wrapper = logService.convertToEntityWrapper("username", logDTO.getUsername());
        wrapper.eq(logDTO.getUserId() != null, "userId", logDTO.getUserId());
        if (logDTO.getUsername()!=null){
            wrapper.eq("username", logDTO.getUsername());
        }
        if (logDTO.getStartTime()!=null&&logDTO.getEndTime()!=null){
            wrapper.between("gmtCreate",logDTO.getStartTime(),logDTO.getEndTime());
        }
        if (logDTO.getOrder()!=null&&logDTO.getOrder()==1){
            wrapper.orderBy("id", true);
        }else {
            wrapper.orderBy("id", false);
        }

        Page<LogDO> page = logService.selectPage(getPage(LogDO.class, logDTO.getPageNum(), logDTO.getPageSize()), wrapper);
        return success(page);
    }

    @Log("删除系统日志")
    @ResponseBody
    @PostMapping("/remove")
    Result<String> remove(Long id) {
        logService.deleteById(id);
        return success();
    }

    @ResponseBody
    @PostMapping("/batchRemove")
    @ApiOperation("批量删除系统日志")
    @Log("批量删除系统日志")
    Result<String> batchRemove(@RequestBody Long[] ids) {
        logService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }

    //下载日志文件
    @ResponseBody
    @GetMapping("/downLoadLog")
    @ApiOperation("导出日志")
    @Log("导出日志")
    public Result<Object> downLoadLog(HttpServletResponse response) {

        // 创建workbook相当于创建一个excel文件
        XSSFWorkbook workbook = new XSSFWorkbook();
        // sheet相当于excel表格中下方的不同的表
        XSSFSheet sheet = workbook.createSheet();
        //查询日志
        List<LogDO> logs = logService.selectList(null);

        // Row则对应Excel中的行，初始化所有行
        int size = logs.size();
        Row[] row = new Row[size + 1];
        for (int i = 0; i < size + 1; i++) {
            row[i] = sheet.createRow(i);
        }

        // Cell相当于单元格，也可以理解为列。因为数据需要三列，所以此处创建了3列
        // 第一行设值
        row[0].createCell(0).setCellValue("用户");
        row[0].createCell(1).setCellValue("操作");
        row[0].createCell(2).setCellValue("接口");
        row[0].createCell(3).setCellValue("ip");
        row[0].createCell(4).setCellValue("时间");
        row[0].createCell(5).setCellValue("参数");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 从第二行开始设置值
        for (int i = 0; i < size; i++) {
            LogDO log = logs.get(i);
            row[i + 1].createCell(0).setCellValue(log.getUsername());
            row[i + 1].createCell(1).setCellValue(log.getOperation());
            row[i + 1].createCell(2).setCellValue(log.getMethod());
            row[i + 1].createCell(3).setCellValue(log.getIp());
            row[i + 1].createCell(4).setCellValue(simpleDateFormat.format(log.getGmtCreate()));
            row[i + 1].createCell(5).setCellValue(log.getParams());
        }

        try (ServletOutputStream outputStream = response.getOutputStream()) {
            String fileName = URLEncoder.encode("log.xlsx", "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.ok();
    }

    @ResponseBody
    @GetMapping("/deleteAll")
    @ApiOperation("清空全部日志")
    @Log("清空全部日志")
    public Result<Object> deleteAll() {

        logService.delete(null);
        return Result.ok();
    }
    //获取登录锁定次数
    @GetMapping("/getlock")
    @ResponseBody
    public Result<Object> getlock() {

        return Result.ok(LoginConfig.loginNum);
    }
    //设置登录锁定次数
    @GetMapping("/setlock")
    @ResponseBody
    public Result<Object> setlock(Integer loginNum) {

        if (loginNum!=null&&loginNum!=0){
            LoginConfig.loginNum = loginNum;
        }else {
            return Result.fail();
        }
        return Result.ok();
    }

    //发送日志接口  将日志发送到syslog服务器
    @GetMapping("/sendLog")
    @ResponseBody
    public Result<Object> sendLog( String ip , Integer port) {

        List<LogDO> logs = logService.selectList(null);

        SyslogIF syslog = Syslog.getInstance(SyslogConstants.UDP);
        syslog.getConfig().setHost(ip);
        syslog.getConfig().setPort(port);
        syslog.getConfig().setMaxMessageLength(Integer.MAX_VALUE);
        StringBuffer buffer = new StringBuffer();
        buffer.append(JSON.toJSONString(logs));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", buffer.toString());

        try {
            syslog.log(0, URLDecoder.decode(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            System.out.println("generate log get exception " + e);
        }
        //System.out.println("哎呀，老z子的第一次dating，竟然还得先搭讪!");
        return  Result.ok();
    }

}
